package com.stn.zjx.givingtreasure.fragment.importwallet;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.bi.BiMainActivity;
import com.stn.zjx.givingtreasure.activity.web.GenericWebActivity;
import com.stn.zjx.givingtreasure.base.BaseImportFragment;
import com.stn.zjx.givingtreasure.domain.ImportEthDomain;
import com.stn.zjx.givingtreasure.event.CreateImportEthWalletEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshWalletEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.GGTApi;
import com.stn.zjx.givingtreasure.net.impl.EthNetImpl;
import com.stn.zjx.givingtreasure.service.WalletUserService;
import com.stn.zjx.givingtreasure.table.WalletUser;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.EventBus;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class ImportPrivatekeyFragment extends BaseImportFragment {

    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.name_edit)
    EditText nameEdit;
    @BindView(R.id.password_edit)
    EditText passwordEdit;
    @BindView(R.id.password_tip)
    TextView passwordTip;
    @BindView(R.id.confirmpassword_edit)
    EditText confirmpasswordEdit;
    @BindView(R.id.info_tv)
    EditText infoTv;
    @BindView(R.id.agree_cb)
    CheckBox agreeCb;
    @BindView(R.id.service_bt)
    TextView serviceBt;
    @BindView(R.id.create_bt)
    Button createBt;


    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        if (rootView == null) {
            rootView = View.inflate(activity, R.layout.fragment_import_wallet_privatekey, null);
            ButterKnife.bind(this, rootView);

        }
        return rootView;
    }

    @Override
    public void initData() {
        createBt.setClickable(false);
        agreeCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    createBt.setBackgroundResource(R.drawable.shape_coloraccent_5dp);
                    createBt.setClickable(true);
                } else {
                    createBt.setBackgroundResource(R.drawable.shape_round_font_lightgray_5dp);
                    createBt.setClickable(false);
                }
            }
        });
        passwordEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    if(!TextUtils.isEmpty(passwordEdit.getText().toString().trim())){
                        if(ToolsUtils.checkUserPassword(passwordEdit.getText().toString().trim())){
                            passwordTip.setVisibility(View.GONE);
                        }else{
                            passwordTip.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }


    @OnClick({R.id.service_bt, R.id.create_bt})
    public void onViewClicked(View view) {
        Bundle bundle=new Bundle();
        switch (view.getId()) {

            case R.id.service_bt:
                bundle.putString("url", GGTApi.service_agreement);
                RxActivityTool.skipActivity(activity, GenericWebActivity.class, bundle);
                break;
            case R.id.create_bt:
                if(TextUtils.isEmpty(content.getText().toString().trim())){
                    activity.showToast(getString(R.string.private_content));
                    return;
                }
                if(TextUtils.isEmpty(nameEdit.getText().toString().trim())){
                    activity.showToast(getString(R.string.please_input_wallet_name));
                    return;
                }
                if(!ToolsUtils.checkName(nameEdit.getText().toString().trim())){
                    activity.showToast(getString(R.string.wallet_name_pattern));
                    return;
                }
                if(TextUtils.isEmpty(passwordEdit.getText().toString().trim())){
                    activity. showToast(getString(R.string.please_inputpassword));
                    return;
                }
                if(!ToolsUtils.checkUserPassword(passwordEdit.getText().toString().trim())){
                    activity. showToast(getString(R.string.password_validate));
                    return;
                }
                if(TextUtils.isEmpty(confirmpasswordEdit.getText().toString().trim())){
                    activity.  showToast(getString(R.string.please_input_repeat_password));
                    return;
                }
                if(!TextUtils.equals(passwordEdit.getText().toString().trim(),confirmpasswordEdit.getText().toString().trim())){
                    activity.showToast(getString(R.string.password_confirm_is_equals));
                    return;
                }
                importPrivatekey(
                        nameEdit.getText().toString().trim(),
                        content.getText().toString().trim(),
                        passwordEdit.getText().toString().trim(),
                        infoTv.getText().toString()
                );
                break;
        }
    }
    public void importPrivatekey(String walletName,String content,String walletPassword,String tip){
        EthNetImpl
                .import_eth_privatekey(content,walletPassword, "import_eth_privatekey", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        activity. showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        activity.dissmissLoading();
                    }
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !activity.isFinishing()) {
                            ImportEthDomain domain=new Gson().fromJson(response.body(),ImportEthDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    WalletUser walletUser=new WalletUser();
                                    walletUser.setAddress(domain.getData().getAddress());
                                    walletUser.setMnemonic("");
                                    walletUser.setName(walletName);
                                    walletUser.setPassword(walletPassword);
                                    walletUser.setTradepassword(walletPassword);
                                    walletUser.setPrivate_key("");
                                    walletUser.setTipmessage(tip);
                                    walletUser.setWallet_type(0);
                                    walletUser.setType(0);
                                    WalletUser db_user = WalletUserService.getInstance(activity)
                                            .getWalletUser(domain.getData().getAddress());
                                    if(db_user!=null){
                                        activity.showToast(getString(R.string.check_alreay_wallet_addrsss));
                                        WalletUser update=WalletUserService.getInstance(activity)
                                                .updateWalletUser(walletUser);
                                        if(update!=null){
                                            if(WalletUserService.getInstance(activity)
                                                    .getAddressCount()==1){
                                                RxActivityTool.skipActivity(activity,BiMainActivity.class);
                                            }
                                            RefreshWalletEvent refreshWalletEvent=new RefreshWalletEvent();
                                            refreshWalletEvent.flag=RefreshWalletEvent.INITREFRESH;
                                            EventBus.getDefault().post(refreshWalletEvent);
                                            CreateImportEthWalletEvent event=new CreateImportEthWalletEvent();
                                            EventBus.getDefault().post(event);


                                            Set<String> sets=new HashSet<String>();
                                            String alias_address=domain.getData().getAddress().substring(2,domain.getData().getAddress().length());
                                            sets.add(alias_address+"");
                                            JPushInterface.addTags(activity,1,sets);
                                            activity.finish();
                                        }else{
                                            activity.showToast(getString(R.string.db_error));
                                        }
                                    }else{
                                        if(WalletUserService.getInstance(activity)
                                                .save(walletUser)){
                                            if(WalletUserService.getInstance(activity)
                                                    .getAddressCount()==1){
                                                RxActivityTool.skipActivity(activity,BiMainActivity.class);
                                            }
                                            RefreshWalletEvent refreshWalletEvent=new RefreshWalletEvent();
                                            refreshWalletEvent.flag=RefreshWalletEvent.INITREFRESH;
                                            EventBus.getDefault().post(refreshWalletEvent);
                                            CreateImportEthWalletEvent event=new CreateImportEthWalletEvent();
                                            EventBus.getDefault().post(event);


                                            Set<String> sets=new HashSet<String>();
                                            String alias_address=domain.getData().getAddress().substring(2,domain.getData().getAddress().length());
                                            sets.add(alias_address+"");
                                            JPushInterface.addTags(activity,1,sets);
                                            activity.finish();
                                        }else{
                                            activity.showToast(getString(R.string.db_error));
                                        }
                                    }
                                    break;
                                default:
                                    activity.showToast(domain.getMessage());
                                    break;
                            }
                        }

                    }
                });
    }
}
